﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ZHDJ.Data;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;
using ZHDJ.Data.Models.Center;
using ZHDJ.Data.BLL;
using System.Runtime.Serialization.Json;
using System.Reflection;
using System.Web.Script.Serialization;
using System.IO;

namespace ZHDJ.Web.WS
{
    /// <summary>
    /// CityOnLineCount 的摘要说明
    /// </summary>
    public class CityOnLineCount : IHttpHandler
    {
        #region 属性
        public static AppBoxContext DB
        {
            get
            {
                if (!HttpContext.Current.Items.Contains("__AppBoxContext"))
                {
                    HttpContext.Current.Items["__AppBoxContext"] = new AppBoxContext();
                }
                return HttpContext.Current.Items["__AppBoxContext"] as AppBoxContext;
            }
        }
        #endregion

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string datetime = context.Request.Form["datetime"];
            string type = context.Request.Form["type"];
            string title = context.Request.Form["title"];
            string branchID = context.Request.Form["branchID"];
            string username = context.Request.Form["username"];

            if (type == "1")
            {
                context.Response.Write(GetPartyVisitStatisticsOnline(datetime, title));
            }
            else if (type == "2")
            {
                context.Response.Write(GetPartyVisitStatisticsLogin(datetime, title));
            }
            else if (type == "3")
            { context.Response.Write(GetSumOrganizationPerson()); }

            else if (type == "4")
            { context.Response.Write(StatisticsSummary()); }

            else if (type == "5")
            { context.Response.Write(GetMemberCost(branchID, username)); }

            else if (type == "6")
            {

            }
        }

        #region 获取登录人数统计
        /// <summary>
        /// 获取登录人数统计
        /// </summary>
        /// <param name="datetime">日期</param>
        /// <param name="title">组织名称</param>
        /// <returns></returns>
        private string GetPartyVisitStatisticsLogin(string datetime, string title)
        {
            StringBuilder json = new StringBuilder();
            StringBuilder pcjson = new StringBuilder();
            StringBuilder appjson = new StringBuilder();
            DataTable dt = GetDataLogin(datetime, title);
            DataTable appdt = new DataTable();
            //APP登录统计数据
            appdt = GetAPPDataLogin("");
            if (dt.Rows.Count > 0)
            {
                json.Append("[");

                //演示用的假数据
                Random rd = new Random();

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow dr = dt.Rows[i];
                    if (i > 0)
                    {
                        json.Append(",");
                        pcjson.Append(",");
                        appjson.Append(",");
                    }
                    //pcjson.Append(dr["psum"]);

                    var pcRan = rd.Next(10, 100);
                    var appRan = rd.Next(10, 100);

                    pcjson.Append(pcRan);

                    DataRow[] drArray = appdt.Select("BranchID='" + dr["BranchID"].ToString() + "'");
                    if (drArray.Count() > 0)
                    {
                        //int sum = Convert.ToInt32(dr["psum"]) + Convert.ToInt32(drArray[0]["psum"]);
                        int sum = pcRan + appRan;

                        //appjson.Append(drArray[0]["psum"]);
                        appjson.Append(appRan);

                        json.Append("['" + dr["BranchName"].ToString().Replace("党支部", "").Replace("机关", "") + "', " + sum.ToString() + "]");
                    }
                }
                json.Append("]");
            }
            //将对象序列化json  
            StatisticModel model = new StatisticModel();
            model.Data = json.ToString();
            model.PCData = pcjson.ToString();
            model.APPData = appjson.ToString();
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(StatisticModel));
            //创建存储区为内存流  
            System.IO.MemoryStream ms = new MemoryStream();
            //将json字符串写入内存流中  
            serializer.WriteObject(ms, model);
            System.IO.StreamReader reader = new StreamReader(ms);
            ms.Position = 0;
            string strRes = reader.ReadToEnd();
            reader.Close();
            ms.Close();
            return strRes;
        }
        #endregion

        #region 获取在线人数统计
        /// <summary>
        /// 获取在线人数统计
        /// </summary>
        /// <param name="datetime">日期</param>
        /// <param name="title">组织名称</param>
        /// <returns></returns>
        private string GetPartyVisitStatisticsOnline(string datetime, string title)
        {
            StringBuilder json = new StringBuilder();
            StringBuilder pcjson = new StringBuilder();
            StringBuilder appjson = new StringBuilder();
            DataTable dt;
            DataTable appdt = new DataTable();
            string nowdate = DateTime.Now.ToString("yyyy-MM-dd");
            if (datetime == nowdate)
                dt = GetNowDataLogin(datetime, title);
            else
                dt = GetDataOnline(datetime, title);
            //APP登录统计数据
            appdt = GetAPPDataLogin("");

            json.Append("[");

            //演示用的假数据
            Random rd = new Random();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                if (i > 0)
                {
                    json.Append(",");
                    pcjson.Append(",");
                    appjson.Append(",");
                }
                //pcjson.Append(dr["psum"]);

                var pcRan = rd.Next(10, 100);
                var appRan = rd.Next(10, 100);

                pcjson.Append(pcRan);


                DataRow[] drArray = appdt.Select("BranchID='" + dr["BranchID"].ToString() + "'");
                if (drArray.Count() > 0)
                {
                    //int sum = Convert.ToInt32(dr["psum"]) + Convert.ToInt32(drArray[0]["psum"]);
                    int sum = pcRan + appRan;

                    //appjson.Append(drArray[0]["psum"]);
                    appjson.Append(appRan);

                    json.Append("['" + dr["BranchName"].ToString().Replace("党支部", "").Replace("机关", "") + "', " + sum.ToString() + "]");
                }
            }
            json.Append("]");

            //将对象序列化json  
            StatisticModel model = new StatisticModel();
            model.Data = json.ToString();
            model.PCData = pcjson.ToString();
            model.APPData = appjson.ToString();
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(StatisticModel));
            //创建存储区为内存流  
            System.IO.MemoryStream ms = new MemoryStream();
            //将json字符串写入内存流中  
            serializer.WriteObject(ms, model);
            System.IO.StreamReader reader = new StreamReader(ms);
            ms.Position = 0;
            string strRes = reader.ReadToEnd();
            reader.Close();
            ms.Close();
            return strRes;
        }
        #endregion

        #region 获取各支部总人数
        /// <summary>
        /// 获取各支部总人数
        /// </summary>
        /// <returns></returns>
        private string GetSumOrganizationPerson()
        {

            StringBuilder json = new StringBuilder();
            DataTable dt = GetAllOrganization();
            json.Append("[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                if (i > 0)
                    json.Append(",");

                json.Append("['" + dr["BranchName"].ToString().Replace("党支部", "").Replace("机关", "") + "', " + dr["psum"] + "]");
            }
            json.Append("]");

            return json.ToString();
        }
        #endregion

        #region 统计结果汇总
        private string StatisticsSummary()
        {
            DataTable dt = new DataTable();
            int nowLoginCount = 0;
            int nowOnlineCount = 0;
            //APP登录人数
            int appCount = GetAPPDataLoginByIsLogin().Rows.Count;
            //今日登录数
            dt = GetDataLogin(DateTime.Now.ToString("yyyy-MM-dd"));
            foreach (DataRow dr in dt.Rows)
            {
                nowLoginCount += Convert.ToInt32(dr["psum"]);
            }
            //今日在线人数
            dt = null;
            dt = GetNowDataLogin(DateTime.Now.ToString("yyyy-MM-dd"));
            foreach (DataRow dr in dt.Rows)
            {
                nowOnlineCount += Convert.ToInt32(dr["psum"]);
            }

            var data = DB.PartyVisitStatistics.ToList()[0];

            //string str = string.Format("今日登录数：<span style='color:#000;font-weight:700;'>{0}</span>  在线人数：<span style='color:#000;font-weight:700;'>{1}</span>  总登录数：<span style='color:#000;font-weight:700;'>{2}</span>  今日访问量：<span style='color:#000;font-weight:700;'>{3}</span>  总访问量：<span style='color:#000;font-weight:700;'>{4}</span>", (nowLoginCount + appCount).ToString(), (nowOnlineCount + appCount).ToString(), (data.LoginCount + appCount).ToString(), (data.TodayVisitCount + appCount).ToString(), (data.VisitCount + appCount).ToString());

            //演示用的假数据
            string str = string.Format("今日登录数：<span style='color:#000;font-weight:700;'>{0}</span>  在线人数：<span style='color:#000;font-weight:700;'>{1}</span>  总登录数：<span style='color:#000;font-weight:700;'>{2}</span>  今日访问量：<span style='color:#000;font-weight:700;'>{3}</span>  总访问量：<span style='color:#000;font-weight:700;'>{4}</span>", (1258).ToString(), (1125).ToString(), (data.LoginCount + appCount).ToString(), (2958).ToString(), (data.VisitCount + appCount).ToString());
            return str;
        }
        #endregion

        #region 获取用户党费缴纳信息
        /// <summary>
        /// 获取用户党费缴纳信息
        /// </summary>
        /// <param name="branchID">支部ID</param>
        /// <param name="username">缴费人名称</param>
        /// <returns></returns>
        private string GetMemberCost(string branchID, string username)
        {
            StringBuilder json = new StringBuilder();
            DataTable dt = PartyMemberCost.GetMemberCost(0, 40, branchID, username).Tables[0];

            json.Append("<table class=\"score_rank_table\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"text-align:center; \">");
            json.Append("<tbody>");
            json.Append("<tr><th>缴费人名称</th><th>缴费金额（元）</th><th>缴费日期</th></tr>");
            if (dt.Rows.Count == 0)
            {
                json.Append("<tr>");
                json.Append("<td colspan=\"3\">暂无符合数据！</td>");
                json.Append("</tr>");
            }
            else
            {
                foreach (DataRow dr in dt.Rows)
                {
                    json.Append("<tr>");
                    json.Append(string.Format("<td>{0}</td>", dr["UserName"]));
                    json.Append(string.Format("<td>{0}</td>", dr["Cost"]));
                    json.Append(string.Format("<td>{0}</td>", Convert.ToDateTime(dr["CreateTime"]).ToString("yyyy-MM-dd")));
                    json.Append("</tr>");
                }
            }
            json.Append("</tbody>");
            json.Append("</table>");

            return json.ToString();
        }
        #endregion

        #region 获取数据
        /// <summary>
        ///获取登录人数数据 
        /// </summary>
        /// <param name="datetime">日期</param>
        /// <param name="title">组织名称</param>
        /// <returns></returns>
        private DataTable GetDataLogin(string datetime = "", string title = "")
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" select COUNT(statisic.ID) as psum,branch.BranchName,branch.BranchID from ");

            if (!string.IsNullOrWhiteSpace(title))
                sb.AppendFormat(" (select * from tblPartyOrgBranch AS a where EXISTS(select * from tblPartyOrgBranch b WHERE a.ParentBranchID=b.BranchID) AND a.BranchName LIKE '%{0}%') AS branch ", title);
            else
                sb.Append(" (select * from tblPartyOrgBranch AS a where EXISTS(select * from tblPartyOrgBranch b WHERE a.ParentBranchID=b.BranchID)) AS branch ");

            sb.Append(" LEFT JOIN ");

            if (!string.IsNullOrWhiteSpace(datetime))
                sb.AppendFormat(" (select * from tblpartyvisitstatisticlogin where AddDate='{0}') AS statisic ", datetime);
            else
                sb.Append(" tblpartyvisitstatisticlogin AS statisic ");

            sb.Append(" ON statisic.BranchID=branch.BranchID ");
            sb.Append(" GROUP BY branch.BranchID,branch.BranchName ");

            sb.Append(" Order By  psum desc ");
            return Data.MySqlHelper.ExecuteDataTable(sb.ToString());
        }

        /// <summary>
        /// 获取当天的在线人数
        /// </summary>
        /// <param name="datetime"></param>
        /// <param name="title">组织名称</param>
        /// <returns></returns>
        private DataTable GetNowDataLogin(string datetime = "", string title = "")
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" select COUNT(statisic.ID) as psum,branch.BranchName,branch.BranchID from ");

            if (!string.IsNullOrWhiteSpace(title))
                sb.AppendFormat(" (select * from tblPartyOrgBranch AS a where EXISTS(select * from tblPartyOrgBranch b WHERE a.ParentBranchID=b.BranchID) AND a.BranchName LIKE '%{0}%') AS branch ", title);
            else
                sb.Append(" (select * from tblPartyOrgBranch AS a where EXISTS(select * from tblPartyOrgBranch b WHERE a.ParentBranchID=b.BranchID)) AS branch ");

            sb.Append(" LEFT JOIN ");

            if (!string.IsNullOrWhiteSpace(datetime))
                sb.AppendFormat(" (select * from tblpartyvisitstatisticlogin where IsOnline=TRUE AND AddDate='{0}') AS statisic ", datetime);
            else
                sb.Append(" tblpartyvisitstatisticlogin where IsOnline=TRUE AS statisic ");

            sb.Append(" ON statisic.BranchID=branch.BranchID ");
            sb.Append(" GROUP BY branch.BranchID,branch.BranchName ");
            sb.Append(" Order By  psum desc ");
            return Data.MySqlHelper.ExecuteDataTable(sb.ToString());
        }

        /// <summary>
        /// 获取历史在线人数数据
        /// </summary>
        /// <param name="datetime">日期</param>
        /// <param name="title">组织名称</param>
        /// <returns></returns>
        private DataTable GetDataOnline(string datetime = "", string title = "")
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" select branch.BranchID,branch.BranchName,(CASE WHEN line.OnlineNumber IS NULL THEN 0 ELSE line.OnlineNumber END) as psum from  ");

            if (!string.IsNullOrWhiteSpace(title))
                sb.AppendFormat(" (select * from tblPartyOrgBranch AS a where EXISTS(select * from tblPartyOrgBranch b WHERE a.ParentBranchID=b.BranchID) AND a.BranchName LIKE '%{0}%') AS branch ", title);
            else
                sb.Append(" (select * from tblPartyOrgBranch AS a where EXISTS(select * from tblPartyOrgBranch b WHERE a.ParentBranchID=b.BranchID)) AS branch ");

            sb.Append(" LEFT JOIN ");
            sb.AppendFormat(" (select * from tblpartyvisitstatisticonline where AddDate='{0}') AS line ", datetime);
            sb.Append(" ON branch.BranchID=line.BranchID ");
            sb.Append(" Order By  psum desc ");
            return Data.MySqlHelper.ExecuteDataTable(sb.ToString());
        }

        /// <summary>
        /// 获取APP登录人数（登录及在线）
        /// </summary>
        /// <param name="title">组织名称</param>
        /// <returns></returns>
        private DataTable GetAPPDataLogin(string title = "")
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" SELECT  COUNT(statisic.ID) as psum,branch.BranchName,branch.BranchID FROM ");
            if (!string.IsNullOrWhiteSpace(title))
                sb.AppendFormat(" (select * from tblPartyOrgBranch AS a where EXISTS(select * from tblPartyOrgBranch b WHERE a.ParentBranchID=b.BranchID) AND a.BranchName LIKE '%{0}%') AS branch ", title);
            else
                sb.AppendFormat(" (select * from tblPartyOrgBranch AS a where EXISTS(select * from tblPartyOrgBranch b WHERE a.ParentBranchID=b.BranchID))AS branch ");
            sb.Append(" LEFT JOIN (SELECT * FROM tblpartyvisitstatisticloginapp WHERE IsLogin=1) AS statisic ON statisic.BranchID=branch.BranchID ");
            sb.Append(" GROUP BY branch.BranchID,branch.BranchName ");
            sb.Append(" Order By  psum desc ");
            return Data.MySqlHelper.ExecuteDataTable(sb.ToString());
        }

        /// <summary>
        /// 获取APP已登录人数
        /// </summary>
        /// <returns></returns>
        private DataTable GetAPPDataLoginByIsLogin()
        {
            string sql = " SELECT * FROM tblpartyvisitstatisticloginapp WHERE IsLogin=1 AND UserID <> 'admin' AND BranchID <> '' ";
            return Data.MySqlHelper.ExecuteDataTable(sql);
        }

        /// <summary>
        /// 获取总登录人数
        /// </summary>
        /// <returns></returns>
        private int GetAllLoginNum()
        {
            int count = 0;
            StringBuilder sb = new StringBuilder();
            sb.Append(" select count(ID) as psum from  tblPartyUserLoginLog where tblPartyUserLoginLog.loginid != ''; ");
            DataTable dt = Data.MySqlHelper.ExecuteDataTable(sb.ToString());
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                count = Convert.ToInt32(dr["psum"]);
            }
            return count;
        }

        /// <summary>
        /// 获取今日访问量
        /// </summary>
        /// <returns></returns>
        private int GetTodayVisitCount()
        {
            int count = 0;
            string sql = " select count(ID) as psum from  tblPartyTouristVisit where date(tblPartyTouristVisit.VistitTime)=date(now()); ";
            DataTable dt = Data.MySqlHelper.ExecuteDataTable(sql);
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                count = Convert.ToInt32(dr["psum"]);
            }
            return count;
        }

        /// <summary>
        /// 获取总访问量
        /// </summary>
        /// <returns></returns>
        private int GetALLVisitCount()
        {
            int count = 0;
            string sql = " select count(ID) as psum from  tblPartyTouristVisit; ";
            DataTable dt = Data.MySqlHelper.ExecuteDataTable(sql);
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                count = Convert.ToInt32(dr["psum"]);
            }
            return count;
        }

        /// <summary>
        /// 获取所有的支部人数
        /// </summary>
        /// <returns></returns>
        private DataTable GetAllOrganization()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" select COUNT(member.ID) as psum ,branch.BranchName,branch.BranchID from  ");
            sb.Append(" tblPartyOrgMember as member ");
            sb.Append(" LEFT JOIN ");
            sb.Append(" (select * from tblPartyOrgBranch AS a where EXISTS(select * from tblPartyOrgBranch b WHERE a.ParentBranchID=b.BranchID)) AS branch ");
            sb.Append(" ON member.BranchID=branch.BranchID ");
            sb.Append(" GROUP BY branch.BranchID ");

            DataTable dt = Data.MySqlHelper.ExecuteDataTable(sb.ToString());
            return dt;
        }
        #endregion

        private void AddOnlineStudyScore(string loginid, string title)
        {
            //增加积分
            PartyScoreHelper.Add(() => PartyScoreHelper.AddCourseWareClick(loginid, title));
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }


    }

    /// <summary>
    /// 统计类
    /// </summary>
    public class StatisticModel
    {
        #region 属性
        public string PCData { get; set; }
        public string APPData { get; set; }

        public string Data { get; set; }
        #endregion
    }

}